﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JT_C_JLB
{
    static class JLB_FRAME_Check
    {
        #region define
        private const int FRAME_LEN = 256;

        private const byte FRAME_ID0_off = 0x00;
        private const byte FRAME_ID0_val = 0x99;

        private const byte FRAME_ID1_off = 0x01;
        private const byte FRAME_ID1_val = 0x66;

        private const byte FRAME_ID2_off = 0x02;
        private const byte FRAME_ID2_val = 0xB2;

        private const byte FRAME_ID3_off = 0x03;
        private const byte FRAME_ID3_val = 0xA2;
        #endregion

        #region local
        private static bool check_length(byte[] frameBuf)
        {
            if (frameBuf.Length != FRAME_LEN)
                return false;
            return true;
        }
        private static bool check_crc(byte[] frameBuf)
        {
            List<byte> arrlist = new List<byte>(frameBuf);
            ushort wholeCRC = CRC16.CalculateCRC(arrlist, 0, arrlist.Count - 2);
            if ((wholeCRC & 0xFF) != frameBuf[FRAME_LEN - 2] || (wholeCRC >> 8) != frameBuf[FRAME_LEN-1])
                return false;
            else
                return true;
        }
        private static bool check_ID(byte[] frameBuf)
        {
            if (frameBuf[FRAME_ID0_off] != FRAME_ID0_val ||
                frameBuf[FRAME_ID1_off] != FRAME_ID1_val ||
                frameBuf[FRAME_ID2_off] != FRAME_ID2_val ||
                frameBuf[FRAME_ID3_off] != FRAME_ID3_val)
                return false;
            return true;
        }
        #endregion

        #region global
        public static string check(byte[] frameBuf)
        {
            if (!check_length(frameBuf))
                return "Wrong frame length = " + frameBuf.Length.ToString();
            if(!check_crc(frameBuf))
                return "CRC error ";
            if (!check_ID(frameBuf))
                return "Head ID error, shold be: 99 66 B2 A2";

            return "Frame OK";
        }
        #endregion
        //----------------------------------------------------------
    }
}
